package developerworks.jetty6;



import javax.servlet.http.*;


import org.mortbay.util.ajax.Continuation;
import org.mortbay.util.ajax.ContinuationSupport;


import org.json.*;


public class JabbifyServlet extends HttpServlet {
	public static final int TIMEOUT_SECS = 59;
	public void service(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
		Timey t = new Timey();
		if(! Jabbify.filterVersion(req, res)) return;
		HttpSession session = req.getSession(false);
		if(session == null){
			res.getWriter().flush();
			return;
		}
		Inbox inbox = (Inbox) session.getAttribute("Inbox");
		if(inbox == null){
			res.getWriter().print("alert('your session does not have a user!');");
			res.getWriter().flush();
		}
		String result = "null";
		try{
			result = inbox.getMessages();
		}catch(JSONException e){
			System.out.println(e.toString());
			result = e.toString();
		}
		
		if(result == "null"){ //lets try again when something comes in
			Continuation c = ContinuationSupport.getContinuation(req,null);
			//System.out.println("     postponing:"+user.name+":"+session.getId());
			String referer = req.getParameter("referer");

			if(referer == null){
				referer = req.getHeader("Referer");
			}else{
				//timeout = 29;
			}
			t.end("JabbifyBefore");
			ApplicationAddressBook.addContinuation(c, session, TIMEOUT_SECS);
		}else{
			t.end("JabbifyBefore");
		}
		
		Timey ta = new Timey();
		String callback = req.getParameter("callback");
		String nocallback = req.getParameter("nocallback");
		if(nocallback == null){
			res.setContentType("text/javascript");
			res.getWriter().print(callback+"("+result+")");
		}
		else{
			res.setContentType("text/plain");
			res.getWriter().print(result);
		}
			
	    res.getWriter().flush();
	    ta.end("JabbifyAfter");

	}
	static public String wrap(String data){
		StringBuffer sb = new StringBuffer();
		sb.append("<html>\n");
		sb.append("<script type='text/javascript'>\n");
		sb.append("window.name = document.getElementsByTagName('script')[0]\n");
		sb.append(".innerHTML.match(/temp\\s*=([\\w\\W]*)/)[1];\n");
		sb.append("temp=");
		sb.append(data);
		sb.append("\n");
		sb.append("</script>");
		sb.append("</html>");
		return sb.toString();
	}
	
}
